package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.application.MyApplication;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.engineer.activity.BalanceActivity;
import com.asktgapp.eventbus.HasNewEvent;
import com.asktgapp.eventbus.PersonalCenterEvent;
import com.asktgapp.model.DifferentTypeVO;
import com.asktgapp.model.OpenAuthVO;
import com.asktgapp.model.UserInfoVO;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.AuthenticateActivity;
import com.asktgapp.user.activity.CollectionActivity;
import com.asktgapp.user.activity.ConsumptionRecordActivity;
import com.asktgapp.user.activity.MyFollowActivity;
import com.asktgapp.user.activity.MyPublishActivity;
import com.asktgapp.user.activity.NewWebActivity;
import com.asktgapp.user.activity.OpinionActivity;
import com.asktgapp.user.activity.PersonalInfoActivity;
import com.asktgapp.user.activity.ServiceOrderActivity;
import com.asktgapp.user.activity.SettingActivity;
import com.asktgapp.user.activity.ShareActivity;
import com.asktgapp.user.activity.SystemMessageActivity;
import com.asktgapp.user.activity.UpdateEngineerInfoActivity;
import com.asktgapp.utils.ImageDisplayUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * :新的个人中心
 */

public class NewPersonalCenterFragment extends BaseFragment {
    //    普通用户
    @InjectView(R.id.ivUser)
    ImageView ivUser;
    @InjectView(R.id.mAuth)
    LinearLayout mAuth;
    @InjectView(R.id.tvUserName)
    TextView tvUserName;
    @InjectView(R.id.tvUserTel)
    TextView tvUserTel;
    @InjectView(R.id.llUserHead)
    LinearLayout llUserHead;
    @InjectView(R.id.tvAuth)
    TextView tvAuth;
    //    工程师
    @InjectView(R.id.ivEngineer)
    ImageView ivEngineer;
    @InjectView(R.id.tvEngineerName)
    TextView mEngineerNametv;
    @InjectView(R.id.llEngineerHead)
    LinearLayout llEngineerHead;
    @InjectView(R.id.llAnswerNumber)
    LinearLayout llAnswerNumber;
    @InjectView(R.id.answerNumber)
    TextView answerNumber;
    @InjectView(R.id.tvEngineerTag1)
    TextView mTag1;
    @InjectView(R.id.tvEngineerTag2)
    TextView mTag2;
    @InjectView(R.id.tvFansNumber)
    TextView tvFansNumber;
    @InjectView(R.id.workTime)
    TextView workTime;
    @InjectView(R.id.llWorkTime)
    LinearLayout llWorkTime;
    @InjectView(R.id.rl_personal_money)
    RelativeLayout mEngineerBalance;
    @InjectView(R.id.tv_personal_money)
    TextView mBalance;


    @InjectView(R.id.tvRelease)
    TextView tvRelease;//我的发布
    @InjectView(R.id.tv_personal_attention)
    TextView mAttention;
    @InjectView(R.id.tv_personal_collection)
    TextView mCollection;
    @InjectView(R.id.tvPersonalMessage)
    LinearLayout tvPersonalMessage;
    @InjectView(R.id.tv_personal_opinion)
    TextView mOpinion;
    @InjectView(R.id.tv_personal_aboutus)
    TextView mAboutUS;
    @InjectView(R.id.tv_personal_setting)
    TextView mSetting;
    @InjectView(R.id.tvInvitation)
    TextView tvInvitation;
    @InjectView(R.id.myOrder)
    RelativeLayout myOrder;
    @InjectView(R.id.myShopOrder)
    RelativeLayout myShopOrder;
    @InjectView(R.id.bill)
    RelativeLayout bill;

    @InjectView(R.id.messageNumber)
    TextView messageNumber;
    @InjectView(R.id.ivPersonalMessage)
    ImageView ivPersonalMessage;
    @InjectView(R.id.tvPersonalMessageContent)
    TextView tvPersonalMessageContent;

    private UserInfoVO mUserInfo;

    private String authStatus = "";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_personal_center_engineer, container, false);
        ButterKnife.inject(this, viewGroup);
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        ivEngineer.setOnClickListener(this);
//        tvAuth.setOnClickListener(this);
        tvAuth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (authStatus.equals("0")) {
                    showTost("您的申请正在审核中，不能再次申请！", 1);
                    return;
                }
                startActivity(new Intent(getActivity(), AuthenticateActivity.class));
            }
        });
        mAttention.setOnClickListener(this);
        mCollection.setOnClickListener(this);
        tvPersonalMessage.setOnClickListener(this);
        mOpinion.setOnClickListener(this);
        mAboutUS.setOnClickListener(this);
        mSetting.setOnClickListener(this);
//        mBalance.setOnClickListener(this);
        llEngineerHead.setOnClickListener(this);
        llUserHead.setOnClickListener(this);
        myOrder.setOnClickListener(this);
        myShopOrder.setOnClickListener(this);
        mEngineerBalance.setOnClickListener(this);
        tvRelease.setOnClickListener(this);
        llWorkTime.setOnClickListener(this);
        tvInvitation.setOnClickListener(this);
        bill.setOnClickListener(this);


    }

    public void showEngineer(boolean show) {
        if (show) {
            bill.setVisibility(View.GONE);
            llEngineerHead.setVisibility(View.VISIBLE);
            mEngineerBalance.setVisibility(View.VISIBLE);
            llUserHead.setVisibility(View.GONE);
            llAnswerNumber.setVisibility(View.VISIBLE);
            mAuth.setVisibility(View.GONE);
        } else {
            bill.setVisibility(View.VISIBLE);
            llEngineerHead.setVisibility(View.GONE);
            mEngineerBalance.setVisibility(View.GONE);
            llUserHead.setVisibility(View.VISIBLE);
            llAnswerNumber.setVisibility(View.GONE);
//            mAuth.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void loadData() {
    }

    private void getUserData(final boolean isAuthStatus) {
        if (MyApplication.userIdIsEmpty(getActivity()))
            return;
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        Call<ApiResponseBody<UserInfoVO>> call = apiservice.getUserInfo(params);
        call.enqueue(new Callback<ApiResponseBody<UserInfoVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<UserInfoVO>> call, Response<ApiResponseBody<UserInfoVO>> response) {
                if (response.isSuccessful()) {
                    mUserInfo = response.body().getResult();
                    if (mUserInfo.getHasTixianPwd() == 0) {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_HAS_TX_PWD, false);
                    } else {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_HAS_TX_PWD, true);
                    }
                    if (mUserInfo.getIsEngineer() == 1) {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, true);
                        PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_NAME, mUserInfo.getRealname() + "");

                    } else {
                        PreferencesUtil.putBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER, false);
                        PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_NAME, mUserInfo.getUsername() + "");

                    }
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.KEY_PHONE, mUserInfo.getPhone());
                    PreferencesUtil.putString(getActivity(), PreferencesUtil.HEAD_IMG, mUserInfo.getUserPic());
                    if (!Util.isEmpty(mUserInfo.getAuthStatus())) {
                        authStatus = mUserInfo.getAuthStatus();
                    }

                    setUI(mUserInfo, isAuthStatus);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<UserInfoVO>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
//                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
//                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    private void setUI(UserInfoVO bean, boolean isA) {
        //工程师和普通用户的个人中心界面有较大差异
        //是否是工程师 1：是; 0：不是
        if (mUserInfo.getIsEngineer() == 1) {
            showEngineer(true);
            mBalance.setText(String.valueOf(bean.getMoney()));
            ImageDisplayUtil.loadCircleHeadImage(getActivity(), ivEngineer, bean.getUserPic());
            mEngineerNametv.setText(bean.getRealname());
            if (Util.isEmpty(bean.getLabel())) {
                mTag1.setVisibility(View.GONE);
                mTag2.setVisibility(View.GONE);
            } else {
                String[] str = bean.getLabel().split(",");
                if (str.length == 0) {
                    mTag1.setVisibility(View.GONE);
                    mTag2.setVisibility(View.GONE);
                } else if (str.length == 1) {
                    mTag1.setVisibility(View.VISIBLE);
                    mTag2.setVisibility(View.GONE);
                    mTag1.setText(str[0]);
                } else if (str.length == 2) {
                    mTag1.setVisibility(View.VISIBLE);
                    mTag2.setVisibility(View.VISIBLE);
                    mTag1.setText(str[0]);
                    mTag2.setText(str[1]);
                } else if (str.length > 2) {
                    mTag1.setVisibility(View.VISIBLE);
                    mTag2.setVisibility(View.VISIBLE);
                    mTag1.setText(str[0]);
                    mTag2.setText(str[1]);
                }
            }
            tvFansNumber.setText("粉丝：" + bean.getFollowNum());
            workTime.setText("修改在线时间\n" + bean.getOnlineTime());
//            if (bean.getIsShow() == 0) {
//                llAnswerNumber.setVisibility(View.GONE);
//            } else {
            llAnswerNumber.setVisibility(View.VISIBLE);
            answerNumber.setText(bean.getAnswerNum() + "条");
//            }
        } else {
            showEngineer(false);
            ImageDisplayUtil.loadCircleHeadImage(getActivity(), ivUser, bean.getUserPic());
            tvUserName.setText(bean.getUsername());
            tvUserTel.setText(bean.getPhone());
            // TODO: 2018/2/5 后台接口忘记写了，等后天写好公共接口，获取是否开放工程师认证入口字段 已经写好了
            // mAuth.setVisibility(View.VISIBLE);
            if (isA) {
                if (authStatus.equals("0")) {
                    showTost("您的申请正在审核中，不能再次申请！", 1);
                    return;
                }
                startActivity(new Intent(getActivity(), AuthenticateActivity.class));
            } else {
                Apiservice apiservice = ApiUtil.getInstance().create();
                HashMap params = new HashMap();
                Call<ApiResponseBody<OpenAuthVO>> call = apiservice.isOpenAuth(params);
                call.enqueue(new Callback<ApiResponseBody<OpenAuthVO>>() {
                    @Override
                    public void onResponse(Call<ApiResponseBody<OpenAuthVO>> call, Response<ApiResponseBody<OpenAuthVO>> response) {
                        if (response.isSuccessful()) {
                            OpenAuthVO bean = response.body().getResult();
                            if (bean.getIs_show().equals("0")) {
                                mAuth.setVisibility(View.GONE);
                            } else {
                                mAuth.setVisibility(View.VISIBLE);
                            }
                        } else {
                            showTost(response.raw().message(), 1);
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponseBody<OpenAuthVO>> call, Throwable t) {
                        ApiException exception = ExceptionHandle.handleException(t);
                        if (exception.isTokenInvalid()) {
//                        showUnLoginSnackbar();
                        } else if (exception.isNetConnected()) {
                            showSetNetworkSnackbar();
                        } else {
//                        showTost(exception.getMessage(), 0);
                        }
                    }
                });
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(PreferencesUtil.getString(getContext(), PreferencesUtil.USER_ID))) {
            getUserData(false);
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    notReadMessageNum();
                }
            }, 800);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //头像
            case R.id.llUserHead:
            case R.id.ivEngineer:
                Intent intent = new Intent(getActivity(), PersonalInfoActivity.class);
                intent.putExtra("name", mUserInfo.getUsername());
                intent.putExtra("head", mUserInfo.getUserPic());
                startActivity(intent);
                break;
            //认证成为工程师
            case R.id.tvAuth:
                getUserData(true);
                break;
            //我的关注
            case R.id.tv_personal_attention:
                startActivity(new Intent(getActivity(), MyFollowActivity.class));
                break;
            //我的收藏
            case R.id.tv_personal_collection:
                startActivity(new Intent(getActivity(), CollectionActivity.class));
                break;
            //通知中心
            case R.id.tvPersonalMessage:
                startActivity(new Intent(getActivity(), SystemMessageActivity.class));
//                startActivity(new Intent(getActivity(), MessageCenterActivity.class));
                break;
            //意见反馈
            case R.id.tv_personal_opinion:
                startActivity(new Intent(getActivity(), OpinionActivity.class));
                break;
            //关于我们
            case R.id.tv_personal_aboutus:
//                startActivity(new Intent(getActivity(), AboutUsActivity.class));
                break;
            //通用设置
            case R.id.tv_personal_setting:
                startActivity(new Intent(getActivity(), SettingActivity.class));
                break;
            //账户余额 工程师钱包
            case R.id.rl_personal_money:
                startActivity(new Intent(getActivity(), BalanceActivity.class));
                break;

            case R.id.myOrder://订单
                startActivity(new Intent(getActivity(), ServiceOrderActivity.class));
                break;
            case R.id.myShopOrder://订单
                NewWebActivity.start(getActivity(), "http://shop.jg969.com:90/client/orderlist?id=" + PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID), "购物车");

                break;
            case R.id.tvRelease://我的发布
                startActivity(new Intent(getActivity(), MyPublishActivity.class));
                break;
            case R.id.llWorkTime://工程师修改在线时间
                startActivity(new Intent(getActivity(), UpdateEngineerInfoActivity.class));
                break;

            case R.id.bill://消费记录---普通用户钱包
                startActivity(new Intent(getActivity(), ConsumptionRecordActivity.class));
                break;

            case R.id.tvInvitation:
                Intent share = new Intent(getActivity(), ShareActivity.class);
                share.putExtra("type", -1);
                startActivity(share);
                break;

        }
    }


    //问答相关消息接口
    private void notReadMessageNum() {

        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userId", PreferencesUtil.getString(getContext(), PreferencesUtil.USER_ID));
//        params.put("platform", "0");
//        params.put("deviceId", Utils.getDeviceId(MyApplication.getInstance()));
        params.put("page", 1);
//        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody<DifferentTypeVO>> call = apiservice.notReadMessageNum(params);
        call.enqueue(new Callback<ApiResponseBody<DifferentTypeVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<DifferentTypeVO>> call, Response<ApiResponseBody<DifferentTypeVO>> response) {
//                dismissProgress();
                if (response.isSuccessful()) {
                    DifferentTypeVO bean = response.body().getResult();
                    if (bean != null) {
                        if (bean.getNotReadNum() > 0) {
                            HasNewEvent.postEvent(4);
                            messageNumber.setVisibility(View.VISIBLE);
                            messageNumber.setText(String.valueOf(bean.getNotReadNum()));
                            tvPersonalMessageContent.setText(bean.getContent());
                            if (!TextUtils.isEmpty(bean.getImg())) {
                                ivPersonalMessage.setVisibility(View.VISIBLE);
                                ImageDisplayUtil.loadCircleHeadImage(getActivity(), ivPersonalMessage, bean.getImg());
                            } else {
                                ivPersonalMessage.setVisibility(View.GONE);
                            }
//                            tvQuestionAndAnswer.setText(bean.getUserName());
//                            questionAndAnswerMessageNumber.setVisibility(View.VISIBLE);
//                            ivQuestionAndAnswer.setVisibility(View.VISIBLE);
                        } else {
                            HasNewEvent.postEvent(3);
                            messageNumber.setVisibility(View.INVISIBLE);
                            tvPersonalMessageContent.setText("");
                            ivPersonalMessage.setVisibility(View.GONE);
//                            readAll = false;
//                            tvQuestionAndAnswer.setText("");
//                            questionAndAnswerMessageNumber.setVisibility(View.INVISIBLE);
//                            ivQuestionAndAnswer.setVisibility(View.INVISIBLE);
                        }

                    }
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<DifferentTypeVO>> call, Throwable t) {
//                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void personalCenter(PersonalCenterEvent event) {
        Log.v("danxx", "前台显示 启动个人中心 " + TextUtils.isEmpty(PreferencesUtil.getString(getContext(), PreferencesUtil.USER_ID)));
        if (!TextUtils.isEmpty(PreferencesUtil.getString(getContext(), PreferencesUtil.USER_ID))) {

            getUserData(false);
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    notReadMessageNum();
                }
            }, 800);

        }
    }
}
